package org.csu.lestore.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhenzi.sms.ZhenziSmsClient;
import org.csu.lestore.api.common.CommonResponse;
import org.csu.lestore.api.entity.Account;
import org.csu.lestore.api.entity.Addr;
import org.csu.lestore.api.service.AccountService;
import org.csu.lestore.api.service.AddrService;
import org.csu.lestore.api.service.CartService;
import org.csu.lestore.api.util.RandomUtils;
import org.csu.lestore.api.util.validateCode.IVerifyCodeGen;
import org.csu.lestore.api.util.validateCode.SimpleCharVerifyCodeGenImpl;
import org.csu.lestore.api.util.validateCode.VerifyCode;
import org.csu.lestore.api.vo.AccountVO;
import org.csu.lestore.api.vo.CartVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/account/")
public class AccountController {
    //创建Logger对象
    private static Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private AccountService accountService;
    @Autowired
    private AddrService addrService;

    @PostMapping("login")
    @ResponseBody
    public CommonResponse<AccountVO> login(@RequestParam("username") String username,
                                           @RequestParam("password") String password,
                                           @RequestParam("code") String code,
                                           HttpSession session){
        String verifyCode= (String) session.getAttribute("VerifyCode");
        if (code!=null && code.equalsIgnoreCase(verifyCode)){//判断验证码
            CommonResponse<AccountVO> response = accountService.getAccountByUserName(username,password);//搜索账号
            if (response.isSuccess()) {//若根据账号密码成功获取到账号
                session.setAttribute("login_account", response.getData());//在session里设置
            }
            return response;
        } else {
            return CommonResponse.createForError("验证码错误");
        }
    }
    @PostMapping("loginByPhone")
    @ResponseBody
    public CommonResponse<AccountVO> loginByPhone(@RequestParam("phone") String phone,
                                                  @RequestParam("valiCode") String code,
                                                  HttpSession session){
        JSONObject data= (JSONObject) session.getAttribute("code");
        if(data!=null) {
            String verifyMCode = (String) data.get("code");

            if (code != null && code.equalsIgnoreCase(verifyMCode)) {//判断验证码
                CommonResponse<AccountVO> response = accountService.getAccountByUserTelephone(phone);//搜索账号
                if (response.isSuccess()) {//若根据电话成功获取到账号
                    session.setAttribute("login_account", response.getData());//在session里设置
                }
                return response;
            } else {
                return CommonResponse.createForError("验证码错误");
            }
        }
        return CommonResponse.createForError("请获取验证码");
    }

    @GetMapping("getLoginAccount")
    @ResponseBody
    public CommonResponse<AccountVO> getLoginAccount(HttpSession session){

        AccountVO accountVO= (AccountVO) session.getAttribute("login_account");
        if (accountVO!=null)
                return CommonResponse.createForSuccess(accountVO);
        return CommonResponse.createForError("用户未登录");
    }

    /*@PostMapping("adminLogin")
    @ResponseBody
    public CommonResponse<AccountVO> adminLogin(@RequestParam("userId") int userId,
                                           @RequestParam("password") String password,
                                           @RequestParam("code") String code,
                                           HttpSession session){
        String verifyCode= (String) session.getAttribute("VerifyCode");
        if (code!=null && code.equalsIgnoreCase(verifyCode)){
            CommonResponse<AccountVO> response = accountService.getAccountByUserId(userId,password);
            if (response.isSuccess()) {
                if(response.getData().getStatus()=='M'){//要求登录账号的账号类型为管理员
                    session.setAttribute("login_account", response.getData());
                }else{
                    return CommonResponse.createForError("无权限");
                }
            }
            return response;
        } else {
            return CommonResponse.createForError("验证码错误");
        }
    }*/

    @PostMapping("register")
    @ResponseBody
    public CommonResponse<AccountVO> register(@RequestParam("username") String username,
                                              @RequestParam("password") String password,
                                              @RequestParam("phone") String phone,
                                              @RequestParam("mcode") String mcode,
                                              HttpSession session) {
        JSONObject data= (JSONObject) session.getAttribute("code");
        if(data!=null){
            String verifyMCode = (String) data.get("code");
            if (mcode != null && mcode.equalsIgnoreCase(verifyMCode)){
                Account account = new Account();
                account.setUserName(username);
                account.setPassword(password);
                account.setTelephoneNumber(phone);

                Calendar calendar =Calendar.getInstance();
                Date date = calendar.getTime();
                account.setRegisterDate(date);
                account.setSex('S');//默认性别保密
                account.setStatus('C');

                AccountVO existAccountVO1 = accountService.getAccountByUserTelephone(phone).getData();
                AccountVO existAcccountVO2 = accountService.getAccountByUserName(username).getData();
                if(existAccountVO1!=null||existAcccountVO2!=null){
                    String msg = "";
                    if(existAccountVO1!=null){
                        msg+="电话号已存在";
                    }
                    if(existAcccountVO2!=null){
                        msg+="用户名已存在";
                    }
                    return CommonResponse.createForError(msg);
                }

                Account newAccount = accountService.insertAccount(accountService.accountToAccountVO(account)).getData();
                CommonResponse<AccountVO> response = accountService.getAccountByUserId(newAccount.getUserId());
                if (response.isSuccess()) {
                    session.setAttribute("login_account", response.getData());//登录
                }
                return response;
            }else{
                return CommonResponse.createForError("验证码错误");
            }
        }else {
            return CommonResponse.createForError("请发送验证码");
        }
    }

    @PostMapping("adminRegister")
    @ResponseBody
    public CommonResponse<AccountVO> adminRegister(@RequestParam("username") String username,
                                              @RequestParam("password") String password,
                                              @RequestParam("phone") String phone,
                                              @RequestParam("mcode") String mcode,
                                              HttpSession session) {
        AccountVO loginAccount= (AccountVO) session.getAttribute("login_account");
        if (loginAccount==null||loginAccount.getStatus()!='M'){
            return CommonResponse.createForError("需要管理员权限");
        }

        JSONObject data= (JSONObject) session.getAttribute("code");
        if(data!=null){
            String verifyMCode = (String) data.get("code");
            if (mcode != null && mcode.equalsIgnoreCase(verifyMCode)){
                Account account = new Account();
                account.setUserName(username);
                account.setPassword(password);
                account.setTelephoneNumber(phone);

                Calendar calendar =Calendar.getInstance();
                Date date = calendar.getTime();
                account.setRegisterDate(date);
                account.setSex('S');//默认性别保密
                account.setStatus('M');

                AccountVO existAccountVO1 = accountService.getAccountByUserTelephone(phone).getData();
                AccountVO existAcccountVO2 = accountService.getAccountByUserName(username).getData();
                if(existAccountVO1!=null||existAcccountVO2!=null){//用户名和密码不能重复
                    String msg = "";
                    if(existAccountVO1!=null){
                        msg+="电话号已存在";
                    }
                    if(existAcccountVO2!=null){
                        msg+="用户名已存在";
                    }
                    return CommonResponse.createForError(msg);
                }

                Account newAccount = accountService.insertAccount(accountService.accountToAccountVO(account)).getData();
                CommonResponse<AccountVO> response = accountService.getAccountByUserId(newAccount.getUserId());

                return response;
            }else{
                return CommonResponse.createForError("验证码错误");
            }
        }else {
            return CommonResponse.createForError("请发送验证码");
        }
    }

    @PostMapping("saveAddress")
    @ResponseBody
    public CommonResponse<Addr> saveAddress(@RequestParam("location") String location,
                                            @RequestParam("name") String name,
                                            @RequestParam("address") String address,
                                            @RequestParam("phone") String phone,
                                            HttpSession session){
        //AccountVO la = accountService.getAccountByUserId(12).getData();
        //session.setAttribute("login_account", la);
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if(login_accountVO!=null){
            Addr addr = new Addr();

            addr.setLocation(location);
            addr.setAddress(address);
            addr.setName(name);
            addr.setTelephone(phone);
            addr.setStatus(false);
            addr.setUserId(login_accountVO.getUserId());

            return addrService.insertAddr(addr);
        }

        return CommonResponse.createForError("未登录");
    }

    @GetMapping("getAddressList")//获取登录账号所有的地址
    @ResponseBody
    public CommonResponse<IPage<Addr>> getAddressList(HttpSession session){

        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if(login_accountVO!=null){
            return addrService.getAddrListInPage(1,2147483647,login_accountVO.getUserId());
        }

        return CommonResponse.createForError("未登录");
    }

    @GetMapping("getDefaultAddr")//获取登陆账号默认地址
    @ResponseBody
    public CommonResponse<Addr> getDefaultAddr(HttpSession session){

        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if(login_accountVO!=null){
            return addrService.getDefaultAddrByUserId(login_accountVO.getUserId());
        }

        return CommonResponse.createForError("未登录");
    }

    @PostMapping("setDefaultAddr")//设置登陆账号默认地址
    @ResponseBody
    public CommonResponse<Addr> setDefaultAddr(HttpSession session,@RequestParam int addrId){

        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if(login_accountVO!=null){
            return addrService.setDefaultAddr(login_accountVO.getUserId(),addrId);
        }

        return CommonResponse.createForError("未登录");
    }

    @PostMapping("updateAddr")//修改地址信息
    @ResponseBody
    public CommonResponse<Addr> updateAddr(HttpSession session,@RequestBody Addr addr){

        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if(login_accountVO!=null){
            return addrService.updateAddr(addr);
        }

        return CommonResponse.createForError("未登录");
    }

    @PostMapping("deleteAddr")//删除地址
    @ResponseBody
    public CommonResponse<Addr> deleteAddr(HttpSession session,@RequestParam int addrId){

        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if(login_accountVO!=null){
            return addrService.deleteAddr(addrId);
        }

        return CommonResponse.createForError("未登录");
    }

    @PostMapping("allAddressList")//获取全部地址信息
    @ResponseBody
    public CommonResponse<IPage<Addr>> getAllAddressList(HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            if(login_accountVO.getStatus()=='M'){//需要管理员权限
                return addrService.getAddrListInPage(1,2147483647);
            }
            return CommonResponse.createForError("权限不足");
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @PostMapping("updateAccount")//修改账号信息
    @ResponseBody
    public CommonResponse<Boolean> updateAccount(@RequestBody Account account,
                                           HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if(login_accountVO!=null){
            accountService.updateAccount(account);
            return CommonResponse.createForSuccess(true);
        }

        return CommonResponse.createForError("未登录");

    }

    //头像
    @ResponseBody
    @PostMapping("saveImg")//头像的上传、存储、修改
    public CommonResponse<AccountVO> saveImg(@RequestParam MultipartFile file ,@RequestParam String userId  ,HttpSession session)throws IOException{
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if(login_accountVO==null){
            return CommonResponse.createForError("未登录");
        }

        String filePath=System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\";
        filePath +="user\\";

        File pathFile=new File(filePath);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }

        //获得原始图片的拓展名
//        String originalFileName=file.getOriginalFilename();
        //新的文件名字
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr= formatter.format(date);

        String newFileName  =dateStr+ RandomUtils.randomNumberString(6);

        //封装上传文件位置的全路径
        File targetFile=new File(filePath,newFileName);
        //把本地文件上传到封装上传文件位置的全路径
        file.transferTo(targetFile);
        //设置图片路径，为字符串类型
        //插入数据库 img src : pathFile  user id ->  img
        return accountService.updateAccountImg(Integer.parseInt(userId),newFileName);
    }

    @PostMapping("logOut")
    @ResponseBody
    public CommonResponse<Boolean> logOut(HttpSession session){
        AccountVO accountVO= (AccountVO) session.getAttribute("login_account");
        session.setAttribute("login_account",null);

        if (session.getAttribute("login_account")==null)
            return CommonResponse.createForSuccess(true);
        else
            return CommonResponse.createForError("退出失败");
    }

    @PostMapping("deleteAccount")
    public CommonResponse<Account> deleteAccount(@RequestParam("userId") int userId,HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            if(login_accountVO.getUserId()==userId){//所有账号都可以注销自己，注销后自动登出
                session.setAttribute("login_account",null);
                return accountService.deleteAccount(userId);
            }else if(login_accountVO.getStatus()=='M'){//管理员可以注销任何账号
                return accountService.deleteAccount(userId);
            }else{
                return CommonResponse.createForError("无权限");
            }
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("accountList")//获取全部账号
    @ResponseBody
    public CommonResponse<IPage<AccountVO>> getAccountList(@RequestParam("size") int size,
                                                           @RequestParam("curPage") int curPage,
                                                           HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            if(login_accountVO.getStatus()=='M'){//需要管理员权限
                return accountService.getAccountListInPage(curPage,size);
            }else{
                return CommonResponse.createForError("无权限");
            }
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("accountListByStatus")//获取某种账号类别的账号
    @ResponseBody
    public CommonResponse<IPage<AccountVO>> getAccountListByStatus(@RequestParam("size") int size,
                                                                   @RequestParam("curPage") int curPage,
                                                                   @RequestParam("status") char status,
                                                                   HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            if(login_accountVO.getStatus()=='M'){//需要管理员权限
                return accountService.getAccountListInPage(curPage,size,status);
            }else{
                return CommonResponse.createForError("无权限");
            }
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("accountListWhichStatusIsNot")//获取除某种账号类别外的账号
    @ResponseBody
    public CommonResponse<IPage<AccountVO>> getaccountListWhichStatusIsNot(@RequestParam("size") int size,
                                                                   @RequestParam("curPage") int curPage,
                                                                   @RequestParam("status") char status,
                                                                   HttpSession session){
        AccountVO login_accountVO = (AccountVO) session.getAttribute("login_account");
        if (login_accountVO!=null) {
            if(login_accountVO.getStatus()=='M'){//需要管理员权限
                return accountService.getAccountListInPageF(curPage,size,status);
            }else{
                return CommonResponse.createForError("无权限");
            }
        }
        else{
            return CommonResponse.createForError("未登录");
        }
    }

    @GetMapping("verifyCode")//网页验证码
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {

        IVerifyCodeGen iVerifyCodeGen =  new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = null;

            verifyCode = iVerifyCodeGen.generate(100, 30);

            String code = verifyCode.getCode();

            System.out.println(code);

            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            try {
                response.getOutputStream().write(verifyCode.getImgBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            response.getOutputStream().flush();
        } catch (IOException ignored) {

        }
    }

    //短信平台相关参数
    //这个不用改
    private String apiUrl = "https://sms_developer.zhenzikj.com";
    //榛子云系统上获取
    private String appId = "111134";
    private String appSecret = "MWNiNDQyMWMtODk5ZS00YjExLWE5NjMtNDA3YjQxNzcxZGE5";

    @ResponseBody
    @RequestMapping("sendCode")//手机验证码
    public CommonResponse<Boolean> getCode(@RequestParam String memPhone, HttpSession httpSession){
        try {
            JSONObject json = null;
            //随机生成验证码
            String code = RandomUtils.randomNumberString(6);


            Map<String, Object> params = new HashMap<String, Object>();
            //前台输入的手机号
            params.put("number", memPhone);
            //这个模板id对应的是榛子云个人中心的模板id
            params.put("templateId", 8536);

            String[] templateParams = new String[2];
            templateParams[0] = code;
            templateParams[1] = "5分钟";
            params.put("templateParams", templateParams);
            //将验证码通过榛子云接口发送至手机
            //ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
            //String result = client.send(params);
            //System.out.println(result);
            //json = JSONObject.parseObject(result);
            System.out.println ("手机验证码是:::"+code);
            json = new JSONObject();
            json.put("memPhone",memPhone);
            json.put("code",code);
            json.put("createTime",System.currentTimeMillis());

            // 将认证码存入SESSION
            httpSession.setAttribute("code",json);
            return CommonResponse.createForSuccess(true) ;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse .createForError ("验证出错");
        }
    }

}
